import React, { useEffect, useState } from 'react';
import { Tree, Empty, Spin, AutoComplete, Input, Button } from 'antd';
import { CodeSandboxOutlined } from '@ant-design/icons';
import { Scrollbars } from 'react-custom-scrollbars';

import styles from './projectTree.less';

const { DirectoryTree, TreeNode } = Tree;

declare type Key = string | number;

const ProjectTreeFn = ({
  isBlank,
  projectTree,
  projectSelectKey,
  setProjectSelectKey,
  projectCheckedKey,
  setProjectCheckedKey,
  loading,
}) => {
  const height = isBlank ? 'calc(100vh - 266px)' : 'calc(100vh - 190px)';
  const [searchName, setSearchName] = useState<string>('');

  const handleSearch = (value: string) => {
    setSearchName(value);
  };

  const handleRenderNameRed = (str: string, name = '') => {
    if (!!name && str.includes(name)) {
      const _arr: any[] = [];
      const _strArr = str.split(name);
      _strArr.forEach((item, index) => {
        if (index !== 0) {
          _arr.push(<span style={{ color: 'red' }}>{name}</span>);
        }
        _arr.push(item);
      });
      return _arr;
    }
    return str;
  };

  /** 渲染树节点 */
  const renderTreeNodes = (data, modelColor = '') => {
    return data.map((item) => {
      if (item.childrens instanceof Array && item.childrens.length) {
        return (
          <TreeNode title={handleRenderNameRed(item.name, searchName)} key={item.id} dataRef={item}>
            {renderTreeNodes(item.childrens, modelColor)}
          </TreeNode>
        );
      }
      return (
        <TreeNode
          title={
            <>
              <span>{handleRenderNameRed(item.name, searchName)}</span>
              {item.isModelUpload ? (
                <CodeSandboxOutlined
                  type="code-sandbox"
                  style={{ marginLeft: 8, color: modelColor ? modelColor : '#1890ff' }}
                />
              ) : null}
            </>
          }
          key={item.id}
          dataRef={item}
          isLeaf
        />
      );
    });
  };

  const [expandedKeys, setExpand] = useState<Key[]>([]);
  const [checkedKeys, setCheckedKeys] = useState<Key[] | { checked: Key[]; halfChecked: Key[] }>([]);
  const [checkedNodes, setCheckedNodes] = useState<Key[] | { checked: Key[]; halfChecked: Key[] }>([]);

  const [isLoadBtnDisabled, setDisabled] = useState(true);

  useEffect(() => {
    if (Array.isArray(checkedNodes)&& checkedNodes.filter(item => Boolean(item && item.isModelUpload)).length) {
      setDisabled(false);
    } else {
      setDisabled(true);
    }
  }, [checkedKeys, checkedNodes]);

  const handleClickLoadBtn = () => {};

  const handleCheck = (checkedKeys: React.Key[], info: any) => {
    console.log(checkedKeys, info);
    const { checkedNodes: nodes } = info;
    setCheckedNodes(nodes.map((item:({dataRef:any})) => item.dataRef));
    setCheckedKeys(checkedKeys);
  };

  return (
    <React.Fragment>
      <div className={styles.search}>
        <Input.Search
          placeholder="输入节点名称搜索"
          size="small"
          enterButton
          onSearch={handleSearch}
        />
      </div>
      <Scrollbars style={{ height }} className={styles.container}>
        <Spin spinning={loading} tip="Loading...">
          {projectTree.length ? (
            <DirectoryTree
              defaultExpandAll
              expandedKeys={expandedKeys}
              checkedKeys={checkedKeys}
              selectable={false}
              expandAction={false}
              showIcon={false}
              onExpand={(expandedKeys) => setExpand(expandedKeys)}
              onCheck={handleCheck}
              checkable
            >
              {renderTreeNodes(projectTree)}
            </DirectoryTree>
          ) : (
            <Empty />
          )}
        </Spin>
      </Scrollbars>
      <div className={styles.btn}>
        <Button
          disabled={isLoadBtnDisabled}
          onClick={handleClickLoadBtn}
          type="primary"
          style={{ width: '100%' }}
        >
          加载选中模型
        </Button>
      </div>
    </React.Fragment>
  );
};

export default ProjectTreeFn;
